package com.lawliet.example.util;

import com.lawliet.example.model.system.SysUser;
import com.lawliet.example.model.vo.UserDetailsImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Slf4j
public class Utils {


    /**
     * 获取登录用户名
     */
    public static SysUser getLoginUser() {
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal instanceof UserDetailsImpl userDetails) {
                return userDetails.getUser();
            }
        } catch (Exception e) {
            log.warn("无法从 SecurityContext 获取登录用户", e);
        }
        return null;
    }

    /**
     *
     * @param file 文件流
     * @param imagePath 文件存储位置
     * @return
     * @throws IOException
     */
    public static String saveImage(MultipartFile file,String imagePath) throws IOException {
        //保存文件
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        File storePath = new File(imagePath + fileName);
        file.transferTo(storePath);
        //保存对象
        return fileName;
    }
}
